package com.unibuy.smartdevice.ui.dialog;

import android.content.Context;

import com.unibuy.smartdevice.DialogAbstract;
import com.unibuy.smartdevice.MyApp;
import com.unibuy.smartdevice.R;
import com.unibuy.smartdevice.databinding.DialogCloseAccessCodeBinding;
import com.unibuy.smartdevice.devices.DeviceType;
import com.unibuy.smartdevice.devices.UsbDev;
import com.unibuy.smartdevice.exception.LogsEmptyException;
import com.unibuy.smartdevice.exception.LogsIOException;
import com.unibuy.smartdevice.exception.LogsParseException;
import com.unibuy.smartdevice.exception.LogsSettingEmptyException;
import com.unibuy.smartdevice.exception.LogsUnsupportedOperationException;
import com.unibuy.smartdevice.external.HttpAPI;
import com.unibuy.smartdevice.structure.BuyStructure;
import com.unibuy.smartdevice.tools.HandlerMain;
import com.unibuy.smartdevice.tools.HandlerMainCountdown;
import com.unibuy.smartdevice.tools.HandlerMainScheduler;
import com.unibuy.smartdevice.tools.ToastHandlerMain;
import com.unibuy.smartdevice.tools.Tools;
import com.unibuy.smartdevice.ui.devs.electric.ElectricFragment;

import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.TimeUnit;

public class CloseAccessCodeDialog extends DialogAbstract {
    public enum Option {
        TOAST(0),
        COUNTDOWN_CANCEL(1),
        SET_COUNTDOWN_TEXT(2),
        INVOICE_SUCCESSFUL(4),
        INVOICE_FAILED(5),
        CHANGE_DISPATCH(6),
        CHANGE_BUY(7),
        CHANGE_CHECKOUT(8),
        ;

        private int option;

        public int getOption() {
            return option;
        }

        Option(int option) {
            this.option = option;
        }
    }

    public static final Map<Integer, Option> optionMap = new HashMap<>();
    static {
        for (Option option : Option.values()) {
            optionMap.put(option.getOption(), option);
        }
    }

    @Override
    protected Context setCtx() {
        return getContext();
    }

    @Override
    protected Class<? extends DialogAbstract> setCls() {
        return getClass();
    }

    @Override
    protected HandlerMain setHandlerMain() {
        return new ToastHandlerMain(getCtx(), getLogs()) {
            @Override
            protected void execute(Context context, int commandCode, String message) {
                Option option = optionMap.get(commandCode);

                switch (option) {
                    case TOAST:
                        super.execute(context, commandCode, message);
                        break;
                    case COUNTDOWN_CANCEL:
                        cancelOnThreadCountdown();
                        break;
                    case SET_COUNTDOWN_TEXT:
                        setButtonCancelText(Integer.valueOf(message));
                        break;
                    case INVOICE_SUCCESSFUL:
                        MyApp.getInstance().getInvoiceData().setCarrier(message);
                        MyApp.getInstance().getReportFlowInfoData().setInvoiceInfo("carrier:" + MyApp.getInstance().getInvoiceData().getCarrier());
                        break;
                    case INVOICE_FAILED:
                        break;
                    case CHANGE_DISPATCH:
                        if (isChangeDispatch) {
                            getSrcHandlerMain().start(getClass().getSimpleName(), ElectricFragment.Option.CLOSE_SLOT.getOption(), "close slot");
                            dialogCancel();
                            isChangeDispatch = false;
                        }
                        break;
                }
            }
        };
    }

    private DialogCloseAccessCodeBinding binding;
    private CloseDialogOnThreadHandler closeDialogCountdown;
    private boolean isChangeDispatch;
    private boolean openBarcode;
    private HttpAPI httpAPI;

    public CloseAccessCodeDialog(Context context, HandlerMain srcHandlerMain) {
        super(context, srcHandlerMain);
    }

    @Override
    protected void onCreate(Context context) {
        binding = DialogCloseAccessCodeBinding.inflate(getLayoutInflater());
        setContentView(binding.getRoot());

        isChangeDispatch = true;
        openBarcode = true;
        httpAPI = new HttpAPI(getHandlerMain());

        binding.buttonFinish.setOnClickListener(v -> changeOk());
        binding.buttonCancel.setOnClickListener(v -> dialogCancel());

        closeDialogCountdown = new CloseDialogOnThreadHandler(getHandlerMain());
        closeDialogCountdown.start(40);

        binding.buttonR1.setOnClickListener(v -> {
            String text = binding.editTextNumber.getText().toString();
            binding.editTextNumber.setText(text.substring(0, text.length()-1));
            binding.editTextNumber.setSelection(binding.editTextNumber.getText().length());
            closeDialogCountdown.setCountdown(40);
        });

        binding.buttonC1.setOnClickListener(v -> {
            binding.editTextNumber.setText("");
            closeDialogCountdown.setCountdown(40);
        });

        binding.button10.setOnClickListener(v -> {
            String btnName = binding.button10.getText().toString();
            String text = binding.editTextNumber.getText().toString();
            binding.editTextNumber.setText(text+btnName);
            binding.editTextNumber.setSelection(binding.editTextNumber.getText().length());
            closeDialogCountdown.setCountdown(40);
        });

        binding.button11.setOnClickListener(v -> {
            String btnName = binding.button11.getText().toString();
            String text = binding.editTextNumber.getText().toString();
            binding.editTextNumber.setText(text+btnName);
            binding.editTextNumber.setSelection(binding.editTextNumber.getText().length());
            closeDialogCountdown.setCountdown(40);
        });

        binding.button12.setOnClickListener(v -> {
            String btnName = binding.button12.getText().toString();
            String text = binding.editTextNumber.getText().toString();
            binding.editTextNumber.setText(text+btnName);
            binding.editTextNumber.setSelection(binding.editTextNumber.getText().length());
            closeDialogCountdown.setCountdown(40);
        });

        binding.button13.setOnClickListener(v -> {
            String btnName = binding.button13.getText().toString();
            String text = binding.editTextNumber.getText().toString();
            binding.editTextNumber.setText(text+btnName);
            binding.editTextNumber.setSelection(binding.editTextNumber.getText().length());
            closeDialogCountdown.setCountdown(40);
        });

        binding.button14.setOnClickListener(v -> {
            String btnName = binding.button14.getText().toString();
            String text = binding.editTextNumber.getText().toString();
            binding.editTextNumber.setText(text+btnName);
            binding.editTextNumber.setSelection(binding.editTextNumber.getText().length());
            closeDialogCountdown.setCountdown(40);
        });

        binding.button15.setOnClickListener(v -> {
            String btnName = binding.button15.getText().toString();
            String text = binding.editTextNumber.getText().toString();
            binding.editTextNumber.setText(text+btnName);
            binding.editTextNumber.setSelection(binding.editTextNumber.getText().length());
            closeDialogCountdown.setCountdown(40);
        });

        binding.button16.setOnClickListener(v -> {
            String btnName = binding.button16.getText().toString();
            String text = binding.editTextNumber.getText().toString();
            binding.editTextNumber.setText(text+btnName);
            binding.editTextNumber.setSelection(binding.editTextNumber.getText().length());
            closeDialogCountdown.setCountdown(40);
        });

        binding.button17.setOnClickListener(v -> {
            String btnName = binding.button17.getText().toString();
            String text = binding.editTextNumber.getText().toString();
            binding.editTextNumber.setText(text+btnName);
            binding.editTextNumber.setSelection(binding.editTextNumber.getText().length());
            closeDialogCountdown.setCountdown(40);
        });

        binding.button18.setOnClickListener(v -> {
            String btnName = binding.button18.getText().toString();
            String text = binding.editTextNumber.getText().toString();
            binding.editTextNumber.setText(text+btnName);
            binding.editTextNumber.setSelection(binding.editTextNumber.getText().length());
            closeDialogCountdown.setCountdown(40);
        });

        binding.button19.setOnClickListener(v -> {
            String btnName = binding.button19.getText().toString();
            String text = binding.editTextNumber.getText().toString();
            binding.editTextNumber.setText(text+btnName);
            binding.editTextNumber.setSelection(binding.editTextNumber.getText().length());
            closeDialogCountdown.setCountdown(40);
        });

        new ReadBarCodeOnScheduler(getHandlerMain()).start(5, TimeUnit.SECONDS);
    }

    public class ReadBarCodeOnScheduler extends HandlerMainScheduler {
        public ReadBarCodeOnScheduler(HandlerMain handlerMain) {
            super(handlerMain);
        }

        @Override
        protected HandlerMain setHandlerMain() {
            return getSrcHandlerMain();
        }

        @Override
        protected void execute(HandlerMain handlerMain) {
            try {
                int totalPrice = 0;
                for (BuyStructure buy : MyApp.getInstance().getBuyList()) {
                    totalPrice += buy.getFullPrice();
                }

                UsbDev usbDev = new UsbDev(DeviceType.QRCODE_SCANNER);
                byte[] buffer = new byte[1000];
                usbDev.read(buffer, 100);
                for (int i=0; i<7; i++) {
                    if (isRun() && openBarcode) {
                        int size = usbDev.read(buffer, 5000);
                        if (size > 5) {
                            String barCodeString = new String(buffer, 0, size);
                            getHandlerMain().start(getLogs().getClassName(), getCtx().getString(R.string.receive_barcode)+"："+ Tools.randomReplace(barCodeString, 0.3)+"，"+getCtx().getString(R.string.send_transaction));//收到條碼,送出交易

                            try {
                                MyApp.getInstance().getAccessCodeStructure().setPassCode(barCodeString);
                                httpAPI.checkAccessCode(MyApp.getInstance().getAccessCodeStructure());
                            } catch (LogsParseException | LogsSettingEmptyException e) {
                                getLogs().warning(e);
                            }

                            openBarcode = false;
                        }
                    }
                }
                usbDev.closePort();
            } catch (LogsUnsupportedOperationException | LogsIOException | LogsEmptyException e) {
                getLogs().warning(e);
            }
        }

        @Override
        protected Class<?> setCls() {
            return getClass();
        }
    }

    public void changeOk() {
        try {
            String number = binding.editTextNumber.getText().toString();
            MyApp.getInstance().getAccessCodeStructure().setPassCode(number);
            httpAPI.checkAccessCode(MyApp.getInstance().getAccessCodeStructure());
        } catch (LogsParseException e) {
            throw new RuntimeException(e);
        } catch (LogsSettingEmptyException e) {
            throw new RuntimeException(e);
        }
    }

    public void dialogCancel() {
        closeDialogCountdown.shutdown();
        MyApp.getInstance().getBuyList().clear();
        cancel();
    }

    public void cancelOnThreadCountdown() {
        MyApp.getInstance().getBuyList().clear();
        cancel();
    }

    public void setButtonCancelText(long countdown) {
        binding.buttonCancel.setText(getCtx().getString(R.string.cancel)+"("+countdown+")");
    }

    public static class CloseDialogOnThreadHandler extends HandlerMainCountdown {
        public CloseDialogOnThreadHandler(HandlerMain handlerMain) {
            super(handlerMain);
            handlerMain.start(getClass().getSimpleName(), CheckoutCashDialog.Option.SET_COUNTDOWN_TEXT.getOption(), String.valueOf(getSrcCountdown()));
        }

        @Override
        protected HandlerMain setHandlerMain() {
            return getSrcHandlerMain();
        }

        @Override
        protected void close(HandlerMain handlerMain) {
            handlerMain.start(getClass().getSimpleName(), BuyDialog.Option.COUNTDOWN_CANCEL.getOption(), "close dialog");
        }

        @Override
        protected void execute(long countdown, HandlerMain handlerMain) {
            handlerMain.start(getClass().getSimpleName(), BuyDialog.Option.SET_COUNTDOWN_TEXT.getOption(), String.valueOf(countdown));
        }

        @Override
        protected Class<?> setCls() {
            return getClass();
        }
    }
}
